package cn.itcast.jd.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;

@Component
public class HttpUtils {
    private PoolingHttpClientConnectionManager cm;

    public HttpUtils() {
        this.cm = new PoolingHttpClientConnectionManager();
        this.cm.setMaxTotal(100);
        this.cm.setDefaultMaxPerRoute(10);
    }
    public String sendGet(String url){
        CloseableHttpClient httpClient=HttpClients.custom().setConnectionManager(cm).build();
        HttpGet httpGet=new HttpGet(url);
        httpGet.setConfig(getConfig());
        httpGet.setHeader("Connection","keep-alive");
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36");
        httpGet.setHeader("Cookie","__jdv=122270672|direct|-|none|-|1649681644419; __jdc=122270672; __jda=122270672.164968164441984269430.1649681644.1649681644.1649681644.1; __jdu=164968164441984269430; shshshfpb=ukrRGlvEmyRkogHxLQm3-zw; shshshfp=da738c87c894ecf55b48cf405a165c0f; shshshfpa=2fc708a5-6eb1-0a6c-8703-40cdfe644346-1649582944; ipLoc-djd=22-1930-0-0; areaId=22; 3AB9D23F7A4B3C9B=75AN45XBAHZRIYQ4OSDRBXDXO2HNUKUDNG44QIUH7XS7TVWARVR6Q5P65CB5CINLYJ5BIBPRPUSTDBBQWOSMBUFH4A; wlfstk_smdl=bugchhuk9zepww7fd130qyp2k3zn9luk; TrackID=1gDJq1wTx6b2S5ul1hsFWXEKuatjKMZ8-_mgoh2OPOXl-OdfEmzU2YMhdluu0_FJFfeo0tQVFgqS0L3gDYZca0tzc6cODLUOeVCpHJuh0XhwB9hT_kRaoo8oLRKAGYnLj; thor=9C4B34FBB5AA9DD960A623DE21966000FCF9C921530E483D0B18F4728750E75C459AE4A94D825DB8405EBDDFD455B4F6234CF65263837EFF893BE66469F2BB871CB35BBD5C803DFF2B8E877F2F3777C74F735056919CE18C5AB8F0EC97C4C7DD579518D12CDF988CACECE6A125C7E706115713369FF8AC70496DC031D6A6E90F0E15FC10974D50B99CDD22D772B77FA6871F2055B2E475F9E63AB189EA023EF9; pinId=wdtQGm1J9LXGz9_qNCe_lbV9-x-f3wj7; pin=jd_7fd4378742c09; unick=jd_7fd4378742c09; ceshi3.com=000; _tp=MyO9v5HqGMW8tBYYpEFjyBQnMtKxem7keKSYQPacgnI%3D; logining=1; _pst=jd_7fd4378742c09; __jdb=122270672.4.164968164441984269430|1.1649681644; shshshsID=dd47d032cca03a150dd770a3092f8943_2_1649681785724\n");
        httpGet.setHeader("Accept","*/*");
        httpGet.setHeader("Accept-Encoding","gzip, deflate, br");
        httpGet.setHeader("Accept-Language","zh-CN,zh;q=0.8");
        httpGet.setHeader("Host","p.3.cn");
        httpGet.setHeader("Referer","https://book.jd.com/booktop/0-0-0.html?category=1713-0-0-0-10001-1");
        try(CloseableHttpResponse response=httpClient.execute(httpGet)) {
            if (response.getStatusLine().getStatusCode() == 200) {
                //判断响应体Entity是否不为空，如果不为空就可以使用EntityUtils
                if (response.getEntity() != null) {
                    String content = EntityUtils.toString(response.getEntity(), "utf8");
                    return content;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";

    }
    public String doGetHtml(String url){
        CloseableHttpClient httpClient=HttpClients.custom().setConnectionManager(cm).build();
        HttpGet httpGet=new HttpGet(url);
        httpGet.setConfig(getConfig());
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36");
//        httpGet.setHeader("Host","p.3.cn");
        try(CloseableHttpResponse response=httpClient.execute(httpGet)) {
            if (response.getStatusLine().getStatusCode() == 200) {
                //判断响应体Entity是否不为空，如果不为空就可以使用EntityUtils
                if (response.getEntity() != null) {
                    String content = EntityUtils.toString(response.getEntity(), "utf8");
                    return content;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public String doGetImage(String url){
        CloseableHttpClient httpClient=HttpClients.custom().setConnectionManager(this.cm).build();
        HttpGet httpGet=new HttpGet(url);
        httpGet.setConfig(getConfig());
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36");
//        httpGet.setHeader("Content-type", "application/x-www-form-urlencoded");
        try(CloseableHttpResponse response=httpClient.execute(httpGet)) {
            if (response.getStatusLine().getStatusCode()==200){
                if (response.getEntity()!=null){
                    String extName=url.substring(url.lastIndexOf('.'));
                    String picName=UUID.randomUUID().toString()+extName;
                    OutputStream outputStream=new FileOutputStream(new File("C:\\Users\\文骏豪\\Desktop\\images\\"+picName));
                    response.getEntity().writeTo(outputStream);
                    return picName;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    private RequestConfig getConfig() {
        RequestConfig config= RequestConfig.custom()
                .setConnectTimeout(1000)
                .setConnectionRequestTimeout(500)
                .setSocketTimeout(10000).build();
        return config;
    }

}
